<?php
namespace app\admin\controller;

use app\admin\model\User;
use \think\Controller;
use \think\Loader;
use \think\Request;
use \think\Session;
use \think\Config;
// error_reporting(E_ERROR | E_WARNING | E_PARSE);
class Base extends Controller
{
	protected $current_user = null;//当前登录人信息
    public $now_uri;//当前操作
    public $now_url;//请求路径
    public $privilege_urls = [];//保存去的权限链接
    protected $allowAllAction = [//默认允许路径
    		'admin/login/index',
    ];
    public $ignore_url = [
            'admin/error/forbidden',
            'admin/index/index',
            'admin/index/showuser',
            'admin/login/verify',
            'admin/login/check_verify',
            'admin/login/logout',    
    ];
    
    //最先执行的操作
    protected $beforeActionList = [
    		'first',
    		'second',
    ];
    
    
    public function first(){
    	$this->request = Request::instance();
    	$this->now_uri = $this->request->module() . '/' . $this->request->controller() . '/' . $this->request->action();
    	$this->now_uri = strtolower($this->now_uri);
    	$this->now_url = $this->request->path();
    }

    public function second(){
        // 判断当前的session是否为空
    	$login_status = $this->checkLoginStatus();
    	if (!$login_status ){
    		if (in_array( $this->now_uri,$this->allowAllAction )){
    			return $this->fetch();
    		}else{
                return $this->fetch('login/index');
    		}
    	}
        // dump($this->checkPrivilege($this->now_uri ));die;
    	if( !$this->checkPrivilege($this->now_uri ) ){
    		$this->error('没有权限访问此页面！',url('admin/index/index'));
    		return false;
    	}
    	return true;
    }
    
    //最先执行的操作
    public function __construct()
    {
        parent::__construct();
        //下一步跑到了$beforeActionList执行完了里面的内容才往下走；
        session('body_id', 0);
        $this->assign('base_uri', url($this->now_uri));
        $this->assign('now_uri', $this->now_uri);
        $this->assign('now_url', $this->now_url);
        $this->bodymap['body_id'] = session('body_id');
        $this->user=new User();
        // $this->coretemp = new Core();
        // $this->userole=new Userole();
        // $id = $this->current_user['id'];
        // $current_role = $this->userole->where('userid',$id)->find();
        // $this->assign('current_role',$current_role);
    }

    //验证登录是否有效，返回 true or  false
    protected function checkLoginStatus(){
    	$sessions = $this->request->session('userinfo');
    	if (!empty($sessions)){
    		//获取用户的所有权限
    		$this->current_user=$sessions;//保存用户session
    		return true;
    	}else {
    		return false;
    	}
    }
    
    //取得用户访问权限路径
    protected function getRolePrivilege($uid = 0){
    	if ( !$uid ){
    		$uid=$this->current_user['id'];
            // dump($uid);die;
    	}
    	//取出指定用户的角色
    	$this->userole=Loader::model('Userole');
    	$roles_id_list = $this->userole->where('userid',$uid)->column('rolesid');
        // dump($roles_id_list);die;
    	$privilege_urls= [];
    	if($roles_id_list){//通过角色取出所属权限
    		$this->roleacc=Loader::model('Roleacc');
    		$this->access=Loader::model('Access');
    		$access_id_list_true=array();
    		foreach ($roles_id_list as $jian =>$roles_id){
    			$access_id_list=$this->roleacc->where('roleac_roleid',$roles_id)->column('roleac_ac_id');
    		}																			
            // dump($access_id_list);die;
    		$act=array();
    		foreach ($access_id_list as $access_id){
    			$act_pice=$this->access->where('ac_id', $access_id  )->column('ac_url');
    			$act=array_merge($act,$act_pice);
    		}
            // dump($act);die;
    		if (!empty($act)){
    			foreach ($act as $_item){
    				 $access_act=@json_decode($_item,true);
                     // dump($access_act);die;
    				 $this->privilege_urls=array_merge($this->privilege_urls,$access_act);
    			}
    		}
    	}
        // dump($this->privilege_urls);die;
		//有的角色权限重复，或者错误输入空值，去重去空
    	$this->privilege_urls=array_filter(array_unique($this->privilege_urls));
        // dump($privilege_urls);die;
    	return    $this->privilege_urls;
    }
    
    //检查是否有访问指定链接的权限
    public function checkPrivilege( $url ){
    	//如果是超级管理员 也不需要权限判断
        // && $this->current_user['user_type']=='0' 
        // 注：特殊情况拎出来、如果只检查$this->currunt_user则直接return true && $this->current_user['user_type']=='1'
    	// if( $this->current_user){
    	// 	return true;
    	// }
    	//有一些页面是不需要进行权限判断的
    	if( in_array( $url,$this->ignore_url ) ){
    		return true;
    	}
        // dump(in_array( $url, $this->getRolePrivilege( ) ));die;
    	return in_array( $url, $this->getRolePrivilege( ) );
    }
    
    protected function md5Pwd($param) {
    	return $pwd=md5($param);
    }
    
    protected function dataNow(){
    	return date("y-m-d H:i:s" ,time());
    }
    
    protected function getUserById($id){
        return 	$date=$this->user->where('id',$id)->find();// ->where('status','1')
    }
    
    protected function checkPwd($username,$pwd,$usertype){
    	$pwd = $this->md5Pwd($pwd);
    	$date=$this->user->where('username',$username)->find();
    	if ($pwd==$date['password'] && $date['status']=1 && $usertype==$date['user_type']){
    		return $date;
    	}else{
    		return false;
    	}
    }

    /**
     * 随机字符
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string
     */
    protected function random($length=6, $type='string', $convert=0){

        $config = array(
            'number'=>'1234567890',
            'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );
        
        if(!isset($config[$type])) $type = 'string';
        $string = $config[$type];
        
        $code = '';
        $strlen = strlen($string) -1;
        for($i = 0; $i < $length; $i++){
            $code .= $string{mt_rand(0, $strlen)};
        }
        if(!empty($convert)){
            $code = ($convert > 0)? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

    protected function saveUser($date){
    		if (!empty($date['username'])){
                $date['id'] = $this->random('12');
    		    $date['update_at']=$this->dataNow();
    		    $res=$this->user->save($date);
    	        return $res;
            }
	}
}
